# 水浒传人物统计
import jieba
import csv
import pstats
import profile
class NameCount():
     def getNameTimesSort(self, name_list, txt_path):
         # 添加jieba分词
        mydict = ['及时雨','黑旋风','行者','豹子头','花和尚','智多星','玉麒麟','小旋风','小李广','九纹龙','青面兽','母大虫','母夜叉','王教头','扈三娘','陆虞候']
        for item in mydict:
            jieba.add_word(item)
        #打开并读取txt文件
        txt = open('water.txt','r',encoding='utf-8').read()
         # 定义别名列表
        bieming = [['及时雨','宋江','呼保义','孝义黑三郎','宋公明','宋押司'],['黑旋风','李逵','铁牛'],['武松','武二郎','行者','武行者','武都头'],['豹子头','林冲','林教头'],
                   [ '鲁提辖' ,'鲁达','智深','花和尚','鲁智深'],['智多星','吴用','吴学究','吴加亮','赛诸葛','加亮先生'],['卢俊义','玉麒麟','卢员外'],[ '小旋风','柴进'],
                   ['花荣','小李广'],['九纹龙','史进'],['杨志','杨制使','杨提辖','青面兽'],['顾大嫂','母大虫'],['孙二娘','母夜叉'],['王进','王教头'],['扈三娘','一丈青'],['陆虞候','陆谦']]
        words = jieba.lcut(txt)
        counts = {}
        for word in words:
            if len(word) == 1:
                continue
            else:
                counts[word] = counts.get(word, 0) + 1
        # 计算出场次数（各个别名的合计次数）
        lst = list()
        for i in range(16):
            lt = 0
            for item in bieming[i]:
                lt += counts.get(item, 0)
            lst.append(lt)
        items = list()
        for i in range(16):
            items.append([name_list[i], lst[i]])
        items.sort(key=lambda x: x[1], reverse=True)
        f = open('水浒传人物统计.csv', 'w', newline='', encoding='utf-8')
        csv_writer = csv.writer(f)
        csv_writer.writerow(['水浒传人物统计'])
        csv_writer.writerow(["姓名", "出现次数"])
        for i in range(16):
            word, count = items[i]
            csv_writer.writerow([word, count])
            print("{0:<10}{1:>5}".format(word, count))
        f.close()      
        return items
if __name__ == '__main__':

    # 参与统计的人名列表，可修改成自己想要的列表
    name_list = ['宋江','李逵','武松','林冲','鲁智深','吴用','卢俊义','柴进','花荣','史进','杨志','顾大嫂','孙二娘','王进','扈三娘','陆谦']
    # txt文件所在路径
    txt_path = 'water.txt'
    NameCount().getNameTimesSort(name_list,txt_path)
    print("效能测试：")
    profile.run('NameCount()', 'result')
    # 直接把分析结果打印到控制台
    p = pstats.Stats('result')  # 创建Stats对象
    p.strip_dirs().sort_stats("call").print_stats()  # 按照调用的次数排序
    p.strip_dirs().sort_stats("cumulative").print_stats()  # 按执行时间次数排序
